<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 地区管理 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <!-- <el-form ref="form" :model="form" label-width="98px">
                省
                <el-input v-model="query.name" placeholder="省" class="handle-input mr10"></el-input>
                市
                <el-input v-model="query.name" placeholder="市" class="handle-input mr10"></el-input>
            </el-form> -->
            搜索地区: <el-input v-model="query.name" placeholder="搜索地区" class="handle-input mr10" @change="handleSearch"></el-input>
            搜索城市:
            <el-select v-model="region" placeholder="请选择">
                <el-option key="-1" label="全部" value=""></el-option>
                <el-option
                    v-for="item in getCityData"
                    :key="item.id"
                    :label="item.areaName"
                    :value="item.id"
                    :disabled="cityDisabled"
                ></el-option>
            </el-select>
            &nbsp;&nbsp;
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <div class="div-add" style="display: block">
                <el-button style="margin: 10px 0px" type="primary" @click="addCity">+ 新增地区</el-button>
            </div>

            <!-- // 展示表单 -->
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="index" label="位置" width="50" align="center"> </el-table-column>
                <el-table-column prop="districtCode" label="地区编号" width="100" align="center"></el-table-column>
                <el-table-column prop="districtName" label="所在区" align="center"></el-table-column>
                <el-table-column prop="cityName" label="所在城市" align="center"></el-table-column>
                <el-table-column label="是否推荐展示地" width="150" align="center">
                    <template slot-scope="scope">
                        <span v-if="scope.row.isRecommend == 0">是</span>
                        <span v-else>否</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="300" align="center">
                    <template slot-scope="scope">
                        <el-button type="info" @click="editStatus(scope.$index, scope.row)">修改推荐</el-button>
                        <el-button type="primary" @click="toDetail(scope.$index, scope.row)">查看</el-button>
                        <!-- <el-button type="success" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
                        <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页插件 -->
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="pageNum"
                    :page-size="pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 新增编辑弹出框 -->
        <el-dialog :visible.sync="editVisible" width="60%" @close="dialogEnd">
            <template #title>
                <div>
                    <span v-if="!isEdit">新增地区</span>
                    <span v-else>修改地区</span>
                </div>
            </template>
            <el-form ref="form" :model="form" label-width="98px">
                <el-form-item label="市">
                    <el-select v-model="region" placeholder="请选择">
                        <el-option
                            v-for="item in getCityData"
                            :key="item.id"
                            :label="item.areaName"
                            :value="item.id"
                            @click.native="changeGateway(item)"
                            :disabled="cityDisabled"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="区">
                    <el-select v-model="regions" clearable @clear="clear" placeholder="请选择">
                        <el-option
                            v-for="item in getTownData"
                            :key="item.id"
                            :label="item.areaName"
                            :value="item.id"
                            @click.native="changeGateways(item)"
                        ></el-option>
                    </el-select>
                    <p v-if="setRed != false" style="color: red">*请从新选择,该地区已经添加*</p>
                    <p v-else></p>
                </el-form-item>
                <!-- <el-form-item label="是否推荐展示地">
                    <el-radio-group v-model="isRecommend">
                        <el-radio key="0" :label="0">否</el-radio>
                        <el-radio key="1" :label="1">是</el-radio>
                    </el-radio-group>
                </el-form-item> -->
                <el-form-item label="是否推荐" v-if="isEdit == true">
                    <el-radio-group v-model="editIsRecommend">
                        <el-radio :label="0">是</el-radio>
                        <el-radio :label="1">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="isEdit == false">
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                    <el-button>取消</el-button>
                </el-form-item>

                <!-- 编辑的是否推荐 -->

                <!-- 新增地区临时展示列表 -->
                <el-table
                    :data="addQu"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    v-if="isEdit == false"
                >
                    <el-table-column prop="districtName" label="地区" width="200" align="center"> </el-table-column>
                    <el-table-column prop="districtCode" label="区号" width="180" align="center"> </el-table-column>
                    <el-table-column prop="isRecommend" label="是否推荐" align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.isRecommend == 0">推荐</span>
                            <span v-else>不推荐</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" width="200">
                        <template slot-scope="scope">
                            <el-button type="warning" @click="editRecommend(scope.$index, scope.row)">更改推荐</el-button>
                            <el-button type="danger" @click="DeleteAddQu(scope.$index, scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">保 存</el-button>
            </span>
        </el-dialog>

        <el-dialog title="查看" :visible.sync="checkLook" width="50%">
            <el-form ref="form" :model="checkForm" label-width="120px">
                <el-form-item label="地区名">
                    <el-input v-model="checkForm.districtName" style="width: 250px" disabled></el-input>
                </el-form-item>
                <el-form-item label="是否热门">
                    <el-radio-group v-model="checkForm.isRecommend">
                        <el-radio key="0" :label="0" disabled>是</el-radio>
                        <el-radio key="1" :label="1" disabled>否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="checkLook = false">取 消</el-button>
                <el-button type="primary" @click="cityEdit(form)" v-if="show == 0">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
//import { fetchData } from '../../api/index';
let isRepeat = false;

import axios from 'axios';
export default {
    name: 'city-town-admin',
    data() {
        return {
            show: 1,
            companyLogo: '',
            companyLogoEvent: '',
            companyIntroduceImg: '',
            companyIntroduceImgEvent: '',
            companyPictureImg: '',
            companyPictureImgEvent: '',
            companyProductVideo: '',
            companyIntroduceVideo: '',
            beforeUpload: '',
            companyProductVideoEvent: '',
            companyIntroduceVideoEvent: '',
            query: {
                address: '',
                name: '',
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [
                // {
                //     articleTitle: '标题',
                //     author: '作者',
                //     authorHeadImg: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3405508716,748611278&fm=26&gp=0.jpg',
                //     programaType: '风情'
                // }
            ],
            form: {
                companyDetailIntro: '',
                companyIntroduce: '',
                companyName: '',
                companyLogo: '',
                qrCode: '',
                companyIntroduceImg: '',
                companyIntroduceVideo: '',
                companyPictureImg: '',
                companyProductVideo: ''
            },
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            pageNum: 1,
            pageSize: 10,
            form: {},
            idx: -1,
            id: -1,
            getCityData: [],
            getTownData: [],
            getQuData: [],
            region: '',
            regions: '',
            regionss: '',
            cityId: '',
            townCode: '',
            getShi: [],
            getQu: [],
            allCity: [],
            setRed: false,
            addQu: [],
            isRecommend: 0,
            checkForm: {},
            checkLook: false,
            // 市的禁用
            cityDisabled: false,
            // 是否为编辑状态
            isEdit: false,
            editIsRecommend: '',
            districtId: '',
            myCityId: '',
            guoCityId: '',
            guoQuCode: '',
            guoQuName: '',
            quArr: '',
            isSearch: false
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 遮罩层关闭时清除数据
        dialogEnd() {
            // alert(11)
            this.region = '';
            this.regions = '';
            this.editIsRecommend = '';
            this.cityDisabled = false;
            // this.getCityData = [];
            this.getTownData = [];
            this.addQu = [];
        },
        changeGateway(e) {
            // console.log();
            this.guoCityId = e.id;
            console.log('市eeeeeeeee', e);
            this.cityId = e.areaCode;
            this.getData_s();
            this.getShi = e;
            // this.cityDisabled = true;
            this.regions = '';

            // 提示用户
            if (!this.isEdit) {
                this.$message('只能添加一个市下的多个区哦');
                this.addQu = [];
            }
        },
        // 区的下拉点击
        changeGateways(e) {
            // 点击区禁用市
            // this.cityDisabled = true;
            console.log(e);
            isRepeat = false;
            // alert(e.id);
            // this.myCityId = e.id
            this.guoQuCode = e.sortCode;
            this.guoQuName = e.areaName;
            // alert(e.areaCode)
            console.log('区eeeeeeeee', e);
            this.setRed = false;
            //console.log(e)
            this.townCode = e.areaCode;
            // this.cityId = e.areaCode;
            //this.getData_ss();
            this.getQu = e;
            // this.addQu.unshift({
            //    districtName: e.areaName,
            //    districtCode: e.areaCode,
            //    isRecommend: 1
            // })
            //console.log(this.getQu)
            // axios.get(this.$myUrl.BASEURL + 'district/getDistrictBasicList?cityId=' + this.townId).then((res) => {
            //     console.log('查询地区信息', res);
            //     res.data.data.forEach((item, index) => {
            //         if (item.areaCode == e.areaCode) {
            //             ////console.log('123')
            //             this.setRed = true;
            //         }
            //     });
            // });
        },
        addCity() {
            this.isEdit = false;
            this.editVisible = true;
        },
        clear() {},

        // 弹出框提交按钮
        async onSubmit() {
            // 判断是否重复
            // this.guoQuCode
            const res = await axios.get(this.$myUrl.BASEURL + 'district/getDistrictList?pageNum=0&pageSize=0');
            this.quArr = res.data.data;
            console.log(this.quArr);
            console.log('区号', this.guoQuCode);
            // 判断服务器里有无
            this.quArr.forEach((item) => {
                if (item.districtCode == this.townCode) {
                    isRepeat = true;
                }
            });
            // console.log(quArr);
            this.addQu.forEach((item) => {
                if (this.townCode == item.districtCode) {
                    isRepeat = true;
                }
            });

            // console.log(isRepeat);
            if (this.cityId == '') {
                this.$message.error('请选择城市');
            } else if (this.townCode == '') {
                this.$message.error('请选择区');
            } else if (isRepeat == true) {
                this.$message.error('该地区已重复');
            } else {
                this.addQu.unshift({
                    districtName: this.getQu.areaName,
                    districtCode: this.getQu.areaCode,
                    isRecommend: 1
                });
            }

            // axios.get(this.$myUrl.BASEURL + 'district/getDistrict?districtId=1163').then( res => {
            //     console.log('地区信息', res);
            // })
            // if (this.addQu == '') {
            //     this.addQu.push({
            //         cityname: this.getShi.areaName,
            //         districtName: this.getQu.areaName,
            //         districtCode: this.getQu.areaCode,
            //         isRecommend: this.isRecommend
            //     });
            // } else {
            //     this.addQu.forEach((item, index) => {
            //         //console.log(item.areaCode)
            //         //console.log(this.getQu.areaCode)
            //         if (item.areaCode != this.getQu.areaCode) {
            //             //this.addQu.splice(item,1)
            //             this.addQu.push({
            //                 cityname: this.getShi.areaName,
            //                 districtName: this.getQu.areaName,
            //                 districtCode: this.getQu.areaCode,
            //                 isRecommend: this.isRecommend
            //             });
            //         }
            //     });
            //     //this.clear()
            // }
            //console.log(this.addQu)
        },

        //  修改本地是否推荐
        editRecommend(index, row) {
            if (row.isRecommend == 0) {
                row.isRecommend = 1;
            } else {
                this.addQu.forEach((item) => {
                    item.isRecommend = 1;
                });
                row.isRecommend = 0;
            }
        },
        DeleteAddQu(index, row) {
            // console.log(index);
            // this.addQu.forEach((item, index) => {
            //     ////console.log(item.areaCode)
            //     ////console.log(this.getQu.areaCode)
            //     if (item.areaCode === row.areaCode) {
            //         this.addQu.splice(item, 1);
            //     }
            // });
            this.addQu.splice(index, 1);
        },
        getData() {
            this.isSearch = false;
            // 进到页面获取地区数据和市级城市
            axios
                .get(this.$myUrl.BASEURL + 'district/getDistrictList?pageNum=' + this.pageNum + '&pageSize=' + this.pageSize)
                .then((res) => {
                    //console.log(res)
                    this.pageTotal = res.data.totalNumber;
                    this.tableData = res.data.data;
                });
            axios.get(this.$myUrl.BASEURL + 'city/getCityBasicList').then((res) => {
                //console.log(res)
                this.getCityData = res.data.data;
            });
        },

        // 获取区的数据
        getData_s() {
            axios.get(this.$myUrl.BASEURL + 'system/findAreaList?areaCode=' + this.cityId).then((res) => {
                console.log(res);
                this.getTownData = res.data.data;
            });
        },

        toDetail(index, row) {
            //console.log(row)
            this.checkLook = true;
            axios.get(this.$myUrl.BASEURL + 'district/getDistrict?districtId=' + row.districtId).then((res) => {
                //console.log(res)
                this.checkForm = res.data.data;
            });
            //this.$router.push('/content-detail');
        },
        // 获取 easy-mock 的模拟数据
        // getData() {
        //     fetchData(this.query).then((res) => {
        //         //console.log(res);
        //         this.tableData = res.list;
        //         this.pageTotal = res.pageTotal || 50;
        //     });
        // },

        // 触发搜索按钮
        handleSearch() {
            
            this.pageNum=1,
            this.isSearch = true;
            this.$set(this.query, 'pageIndex', 1);
            this.tableData = [];
            axios
                .get(
                    this.$myUrl.BASEURL +
                        'district/getDistrictList?districtName=' +
                        this.query.name +
                        '&cityId=' +
                        this.region +
                        '&pageNum=' +
                        this.pageNum +
                        '&pageSize=' +
                        this.pageSize
                )
                .then((res) => {
                    this.cityDisabled = false;
                    console.log('搜索地区结果', res);
                    this.tableData = res.data.data;
                    this.pageTotal = res.data.totalNumber;
                    // res.data.data.forEach((item, index) => {
                    //     this.tableData.push(item);
                    // });
                });
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            //console.log(row)
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    axios.delete(this.$myUrl.BASEURL + 'district/deleteDistrictList?districtIdList=' + row.districtId).then((res) => {
                        //console.log(res)
                    });
                    this.$message.success('删除成功');
                    this.tableData.splice(index, 1);
                })
                .catch(() => {});
        },
        // 修改状态操作
        editStatus(index, row) {
            console.log(row);
            if (row.isRecommend == 0) {
                axios
                    .put(this.$myUrl.BASEURL + 'district/updateDistrictRecommend?districtId=' + row.districtId + '&isRecommend=1')
                    .then((res) => {
                        this.handleSearch();
                    });
            } else {
                axios
                    .put(this.$myUrl.BASEURL + 'district/updateDistrictRecommend?districtId=' + row.districtId + '&isRecommend=0')
                    .then((res) => {
                        this.handleSearch();
                    });
            }
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },

        // 编辑操作
        handleEdit(index, row) {
            console.log(row);

            this.guoQuCode = row.districtCode;
            this.guoQuName = row.districtName;
            this.myCityId = row.districtId;
             this.guoCityId = row.cityId
            // this.myCityId = row.districtId;
            // this.cityName = row.districtCode
            this.districtId = row.districtId;
            this.idx = index;
            this.form = row;
            this.editVisible = true;
            this.isEdit = true;

            axios.get(this.$myUrl.BASEURL + 'district/getDistrictBasicList?cityId=' + row.cityId).then((res) => {
                console.log('1.12.3.地区下拉框', res);
                this.getTownData = res.data.data;
            });

            axios.get(this.$myUrl.BASEURL + 'city/getCity?cityId=' + row.cityId).then((res) => {
                console.log('111111111111111111', res);
                this.region = res.data.data.id;
            });
            axios.get(this.$myUrl.BASEURL + 'district/getDistrict?districtId=' + row.districtId).then((res) => {
                console.log('区', res);
                this.regions = res.data.data.id;
                this.editIsRecommend = res.data.data.isRecommend;
            });
        },
        // 保存编辑
        saveEdit() {
            //this.$set(this.tableData, this.idx, this.form);
            if (!this.isEdit) {
                // 新增
               if (this.addQu.length == 0) {
                   this.$message.error('请添加数据')
               } else {
                    axios
                    .post(this.$myUrl.BASEURL + 'district/addDistrictList', {
                        cityId: this.getShi.id,
                        districtList: this.addQu
                    })
                    .then((res) => {
                        console.log('修改成功返回值', res);
                        // 解除区的禁用
                        this.cityDisabled = false;
                        if (res.data.code == 1004) {
                            this.$message.error(res.data.msg);
                            // 清空数据
                            // this.addQu = [];
                            // this.region = '';
                            // this.regions = '';
                        } else if (res.data.code == 200) {
                            this.$message.success(`保存成功`);
                            this.getData();
                            this.editVisible = false;
                            // 清空数据
                            this.addQu = [];
                            this.region = '';
                            this.regions = '';
                        }
                    });
               }
            } else {
                // alert(11)
                // console.log(this.regions);
                // axios.get(this.$myUrl.BASEURL + 'district/getDistrict?districtId=26').then((res) => {
                //     console.log(res);
                // });
                console.log(this.guoQuCode);
                console.log(this.guoQuName);
                console.log(this.myCityId);
                console.log(this.guoCityId);
                console.log(this.editIsRecommend);
                axios
                    .put(this.$myUrl.BASEURL + 'district/updateDistrict', {
                        id: this.myCityId,
                        cityId: this.guoCityId,
                        districtCode: this.guoQuCode,
                        districtName: this.guoQuName,
                        isRecommend: this.editIsRecommend
                    })
                    .then((res) => {
                        console.log(res);
                        if (res.data.code == 200) {
                            this.getData();
                            this.editVisible = false;
                            this.$message.success('编辑成功');
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    });
            }
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageNum', val);
            this.pageNum = val;
            if (!this.isSearch) {
                this.getData();
            } else {
                this.handleSearch();
            }
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
    border-radius: 50%;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
</style>
